package com.lewis.generator.controller;

import com.lewis.core.annotation.Log;
import com.lewis.core.base.controller.BaseController;
import com.lewis.core.base.domain.BaseResult;
import com.lewis.core.base.page.TableDataInfo;
import com.lewis.core.base.text.Convert;
import com.lewis.core.enums.BusinessType;
import com.lewis.generator.service.IGenTableColumnService;
import com.lewis.generator.service.IGenTableService;
import com.lewis.generator.entity.GenTable;
import com.lewis.generator.entity.GenTableColumn;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 代码生成 操作处理
 *
 * @author Lewis
 */
@RestController
@RequestMapping("/tool/gen")
public class GenController extends BaseController {

	@Resource
	private IGenTableService genTableService;

	@Resource
	private IGenTableColumnService genTableColumnService;

	/**
	 * 查询代码生成列表
	 */
	@GetMapping("/list")
	public TableDataInfo genList(GenTable genTable) {
		startPage();
		return getTableData(genTableService.selectGenTableList(genTable));
	}

	/**
	 * 获取某个表详情
	 */
	@GetMapping(value = "/{id}")
	public BaseResult get(@PathVariable Long id) {
		GenTable table = genTableService.selectGenTableById(id);
		List<GenTable> tables = genTableService.selectGenTableAll();
		List<GenTableColumn> list = genTableColumnService.list(id);
		Map<String, Object> map = new HashMap<>();
		map.put("info", table);
		map.put("rows", list);
		map.put("tables", tables);
		return BaseResult.ok().setData(map);
	}

	/**
	 * 查询数据库列表
	 */
	@GetMapping("/db/list")
	public TableDataInfo dataList(GenTable genTable) {
		startPage();
		return getTableData(genTableService.selectDbTableList(genTable));
	}

	/**
	 * 查询数据表字段列表
	 */
	@GetMapping(value = "/column/{talbleId}")
	public TableDataInfo columnList(Long tableId) {
		TableDataInfo dataInfo = new TableDataInfo();
		List<GenTableColumn> list = genTableColumnService.list(tableId);
		dataInfo.setRows(list);
		dataInfo.setTotal(list.size());
		return dataInfo;
	}

	/**
	 * 导入表结构（保存）
	 */
	@Log(
			title = "代码生成",
			businessType = BusinessType.IMPORT
	)
	@PostMapping("/importTable")
	public BaseResult importTableSave(String tables) {
		String[] tableNames = Convert.toStrArray(tables);
		// 查询表信息
		List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
		genTableService.importGenTable(tableList);
		return BaseResult.ok();
	}

	/**
	 * 修改保存代码生成业务
	 */
	@Log(
			title = "代码生成",
			businessType = BusinessType.UPDATE
	)
	@PutMapping
	public BaseResult editSave(@Validated @RequestBody GenTable genTable) {
		genTableService.validateEdit(genTable);
		genTableService.updateGenTable(genTable);
		return BaseResult.ok();
	}

	/**
	 * 删除代码生成
	 */
	@Log(
			title = "代码生成",
			businessType = BusinessType.DELETE
	)
	@DeleteMapping("/{tableIds}")
	public BaseResult remove(@PathVariable Long[] tableIds) {
		return getResult(genTableService.deleteGenTableByIds(tableIds));
	}

	/**
	 * 预览代码
	 */
	@GetMapping("/preview/{id}")
	public BaseResult preview(@PathVariable("id") Long tableId) {
		return BaseResult.ok().setData(genTableService.previewCode(tableId));
	}

	/**
	 * 生成代码（下载方式）
	 */
	@Log(
			title = "代码生成",
			businessType = BusinessType.GEN_CODE
	)
	@GetMapping("/download/{tableName}")
	public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
		byte[] data = genTableService.downloadCode(tableName);
		genCode(response, data);
	}

	/**
	 * 生成代码（自定义路径）
	 */
	@Log(
			title = "代码生成",
			businessType = BusinessType.GEN_CODE
	)
	@GetMapping("/genCode/{tableName}")
	public BaseResult genCode(@PathVariable("tableName") String tableName) {
		genTableService.generatorCode(tableName);
		return BaseResult.ok();
	}

	/**
	 * 同步数据库
	 */
	@Log(
			title = "代码生成",
			businessType = BusinessType.UPDATE
	)
	@GetMapping("/synchDb/{tableName}")
	public BaseResult synchDb(@PathVariable("tableName") String tableName) {
		genTableService.synchDb(tableName);
		return BaseResult.ok();
	}

	/**
	 * 批量生成代码
	 */
	@Log(
			title = "代码生成",
			businessType = BusinessType.GEN_CODE
	)
	@GetMapping("/batchGenCode")
	public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
		String[] tableNames = Convert.toStrArray(tables);
		byte[] data = genTableService.downloadCode(tableNames);
		genCode(response, data);
	}

	/**
	 * 生成zip文件
	 */
	private void genCode(HttpServletResponse response, byte[] data) throws IOException {
		response.reset();
		response.addHeader("Access-Control-Allow-Origin", "*");
		response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
		response.setHeader("Content-Disposition", "attachment; filename=\"lewis.zip\"");
		response.addHeader("Content-Length", "" + data.length);
		response.setContentType("application/octet-stream; charset=UTF-8");
		IOUtils.write(data, response.getOutputStream());
	}
}